<template>
	<div class="sidebar" ref="sidebar" v-loading="isLoading">
		<el-input
			size="mini"
			placeholder="快速搜索项目名称"
			v-model="filterText"
		/>
		<div style="height:5px;" />
		<el-tree
			class="pt-tree"
			ref="tree"
			:data="projectTreeData"
			node-key="projectId"
			:default-expanded-keys="defaultExpandedKeys"
			highlight-current
			:props="{
				children: 'children',
				label: 'projectName'
			}"
			:filter-node-method="filterNode"
			@node-click="clickProject"
		>
			<div class="el-tree-node__label" slot-scope="{ node, data }">
				<span>{{ node.label }} </span>
				<span v-if="data.projectAvlstatus=='N'" class="navls">禁用</span>
				<span v-if="auditState || qualityStatus" class=" count">{{ data | getCount(resourceVideoCount) }} </span>
			</div>
		</el-tree>
	</div>
</template>

<script>
    import coursewareApi from "@rc/apis/rc/courseware.mjs";
    export default {
        name: "veProTree",
        data() {
            return {
                filterText: '', // 节点过滤
                projectTreeData: [],
                // 默认展开
                defaultExpandedKeys: [],
                resourceVideoCount: [],// 资源数量数组
                isLoading: false
            };
        },
        props: {
            //是否显示全部选项
            totalable: {
                type: Boolean,
                default: false,
            },
            //用户项目权限code
            menuCode: {
                type: String,
                default: null,
            },
            //是否仅显示启用项目
            onlyAvlShow: {
                type: Boolean,
                default: false,
            },
            // 是否显示资源下 ''不展示资源数量  W:展示待审核资源数量、 N:审核不通过
            auditState: {
                type: String,
                default: '',
            },
            qualityStatus:{//质检状态 待质检
                type: String,
                default: '',
            },
            // 默认选中第一个
            defaultChecked:{
                type: Boolean,
                default: false,
            }
        },
        watch: {
            filterText(val) {
                this.$refs.tree.filter(val);
            }
        },
        filters: {
            // 获取项目下资源数量
            getCount: function (project,resourceVideoCount) {
                let projectList = [];
                if(project.children ) { // 学院
                    if(project.children.length) {
                        let enabledProjectList =  project.children.filter(children => children.projectAvlstatus === 'Y');
                        let disabledProject = project.children.find(children => children.disabled === 'disabled');
                        projectList.push(...enabledProjectList);
                        disabledProject && projectList.push(...disabledProject.projectAvlArr);
                    }
                } else {
                    if(project.disabled === 'disabled') {
                        if(project.isCollege) {// 禁用学院
                            project.projectAvlArr.forEach(collcege => {
                                let disabledProject = collcege.children.find(children => children.disabled === 'disabled');
                                disabledProject && projectList.push(...disabledProject.projectAvlArr);
                            });
                        } else { // 禁用项目
                            projectList.push(...project.projectAvlArr);
                        }

                    } else { // 项目
                        projectList.push(project);
                    }
                }
                let resourceIds = [];
                projectList.forEach(project => {
                    let countItem = resourceVideoCount.find(item => item.projectId && item.projectId === project.projectId);
                    const projectResourceIds = countItem?countItem.resourceIds:[];
                    resourceIds = [...resourceIds,...projectResourceIds];
                });
                //资源数量显示为去重后的数量
                resourceIds = [...new Set(resourceIds)];
                return resourceIds.length ? '('+resourceIds.length+')' : '';
            }
        },
        mounted() {
            this.getTreeData().then((treeData) => {
                this.loadTreeData(treeData);
            });
        },
        methods: {
             //获取treeData数据
            getTreeData() {
                let request = [{
                    url: 'bd/project/tree/user',
                    data: {
                        menuCode: this.menuCode,
                    }
                }];
                //查询审核状态下课件数量或者质检状态下的课件数量
                if(this.auditState || this.qualityStatus) {
                    request.push({
                        url: 'rc/admin/resourcevideo/check/project/count/list',
                        data: {
                            auditState:this.auditState,
                            qualityStatus:this.qualityStatus
                        }
                    });
                }
                this.isLoading = true;
                return new Promise(resolve => {
                    Http.callServices(request).success((projectResult, resourceVideoCount)=>{
                        if(resourceVideoCount) {
                            this.resourceVideoCount = resourceVideoCount;
                        }
                        resolve(projectResult.data);
                    }).complete(() => {
                        this.isLoading = false;
                    });
			    });
            },
            loadTreeData(treeData) {
                if(this.totalable){
                    treeData.unshift({
                        projectId:"all",
                        projectName: '全部',
                        isTotal:true,
                        projectAvlstatus:'Y',
                        children:[]
                    });
                }
                this.treeData=treeData;
                this.handletreeData();
            },
            handletreeData() {
                let dataTemp = this.treeData;
                let data = [];
                let hasAvlstatus = dataTemp.some((item) => item.projectAvlstatus === 'N');
                let projectAvlArr = [];
                data = dataTemp.filter((item) => {
                    return item.projectAvlstatus === 'Y';
                });
                projectAvlArr = dataTemp.filter((item) => {
                    return item.projectAvlstatus === 'N';
                });
                dataTemp.forEach((item1) => {
                    let item1Temp = item1.children || [];
                    let hasAvlstatus = item1Temp.some((item2) => {
                        return item2.projectAvlstatus === 'N';
                    });
                    item1.children = item1Temp.filter((item3) => {
                        return item3.projectAvlstatus === 'Y';
                    });
                    let projectAvlArr = [];
                    projectAvlArr = item1Temp.filter((item) => {
                        return item.projectAvlstatus === 'N';
                    });
                    if (!this.onlyAvlShow && hasAvlstatus) {
                        item1.children.push({
                            projectName: '禁用项目',
                            isProject: true,
                            disabled: 'disabled', //避免与接口返回的disabled:true交叉影响
                            projectAvlArr
                        });
                    }
                });
                if (!this.onlyAvlShow && hasAvlstatus) {
                    data.push({
                        projectName: '禁用学院',
                        isCollege: true,
                        disabled: 'disabled',
                        projectAvlArr
                    });
                }
                this.projectTreeData = data;
                // 判断是否默认选中第一个项目
                {
                    if(this.totalable && this.defaultChecked) {
                        this.$nextTick(() => {
                            let item = dataTemp[0];
                            this.$refs['tree'].setCurrentKey(item.projectId);
                            this.clickProject(item, {level: 1});
                        });
                        return;
                    }
                    this.defaultChecked && this.fomat(this.projectTreeData || []);
                }
            },
            fomat(list) {
                        for (let i = 0; i < list.length; i++) {
                            let item = list[i];
                            if (!item.children) {
                                if (item.projectId != 'PROJECT00000000000000000000') {
                                    this.defaultExpandedKeys.push(item.projectId);
                                    this.$nextTick(() => {
                                        this.$refs['tree'].setCurrentKey(item.projectId);
                                        this.clickProject(item, {level: 2});
                                        this.$emit('ready',item);
                                    });
                                    break;
                                }
                            } else {
                                this.fomat(item.children);
                                break;
                            }
                        }
            },
            filterNode(value, data) {
                if (!value) return true; // 清空是展示所有
                return data.projectName.indexOf(value) !== -1; // 一个一个节点去匹配，匹配到展示。否则不展示
            },
            clickProject(item, a) {
                if (item.disabled === 'disabled') {
                    if (a.level == 1) {
                        if(this.projectTreeData[this.projectTreeData.length-1].projectName === '禁用学院') {//展开
                            this.projectTreeData.push(...item.projectAvlArr);
                        }else{//收起
                             this.projectTreeData.splice(this.projectTreeData.length -item.projectAvlArr.length, item.projectAvlArr.length);
                        }
                    } else if (a.level == 2) {
                        if (item.projectName === '禁用项目') {
                            let projectId = a.parent.data.projectId;
                            this.projectTreeData.forEach((item1) => {
                                if (item1.projectId === projectId) {
                                    if( item1.children[item1.children.length - 1].projectName === '禁用项目') {//展开
                                        item1.children.push(...item.projectAvlArr);
                                    } else { //收起
                                        item1.children.splice(item1.children.length- item.projectAvlArr.length, item.projectAvlArr.length);
                                    }
                                    // 解决选中禁用项目下的项目后，禁用项目被选中的问题
                                    if(this.checkItem && item.projectAvlArr.find(item => item.projectId === this.checkItem.projectId)) {
                                        this.checkItem = {};
                                    }
                                }
                            });
                        }
                    }
                    this.checkItem && this.$refs.tree.setCurrentKey(this.checkItem.projectId);
                }else if(item.isTotal){
                    if (this.checkItem == item) {
                        return;
                    }
                    this.checkItem = item;
                    this.$emit('choose', {});
                } else if (a.level == 1) {
                    this.$refs.tree.setCurrentKey((this.checkItem||{}).projectId);
                } else if (a.level == 2) {
                    if (this.checkItem == item) {
                        return;
                    }
                    this.checkItem = item;
                    this.$emit('choose', item);
                }
            },
            api_getCurrentNode() {
				return this.$refs.tree.getCurrentNode();
			},
            /**
             * 获取资源数量
             */
            api_getProjectCount() {
                coursewareApi.queryProjectResourceVideoCount({
                    data: {
                       auditState:this.auditState,
                       qualityStatus:this.qualityStatus
                    },
                    success: (resourceVideoCount) => {
                       this.resourceVideoCount = resourceVideoCount;
                    }
                });
            },
        }
    };
</script>

<style scoped  lang="less">
    /*项目树*/
    .sidebar {
        padding: 0 10px;
        flex: none;
        background-color: #fff;
        .pt-tree{
            overflow-y: auto;
        }
        .count,.navls{
            font-size: 12px;
            color:#F73951;

        }
        .count{
          padding-right: 5px;
          float: right;
        }
        .navls{
            margin-left: 5px;
        }
        /deep/ .el-tree-node__content{
            display: flex;
        }
        /deep/ .el-tree-node__label{
            flex:1;
        }
        /deep/ .el-tree-node.is-current .count,.el-tree-node.is-current .navls{
            color:#fff;
        }
        & /deep/ [aria-disabled="disabled"] .el-tree-node__label {
            color: #F73951;
        }
    }
</style>
